﻿// Copyright (c) 2014 Converter Systems LLC

using System;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace ConverterSystems.UaBrowser.Data
{
    [ValueConversion(typeof(Type), typeof(String))]
    public class TypeToStringConverter : ValueConverter<Type, String>
    {
        protected override String Convert(Type value, object parameter, CultureInfo culture)
        {
            return FormatTypeName(value);
        }

        private string FormatTypeName(Type type)
        {
            if (type == null) return string.Empty;
            if (!type.IsGenericType) return type.Name;
            if (type.IsNested && type.DeclaringType.IsGenericType) throw new NotImplementedException();
            StringBuilder txt = new StringBuilder();
            txt.Append(type.Name, 0, type.Name.IndexOf('`'));
            txt.Append("<");
            txt.Append(string.Join(", ", type.GetGenericArguments().Select(arg => FormatTypeName(arg))));
            txt.Append(">");
            return txt.ToString();
        }
    }
}